package com.gitee.mrj.aiboot.core.sf.generators.ui;

import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.gitee.mrj.aiboot.annotation.config.sf.ui.ACLType;
import com.gitee.mrj.aiboot.core.sf.generators.FormDefinitionGenerator;
import com.gitee.mrj.aiboot.core.sf.generators.UIForm;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
public class ACLTypeGenerator implements FormDefinitionGenerator {
    @Override
    public void generate(UIForm root, Field field, UIForm node) {
        ACLType aclType = AnnotatedElementUtils.findMergedAnnotation(field, ACLType.class);
        ObjectNode ui = node.getUi();
        ObjectNode acl = ui.putObject("acl");

        String[] role = aclType.role();
        if (ArrayUtils.isNotEmpty(role)) {
            ArrayNode roles = putArray(acl, "role");
            for (String r : role) {
                roles.add(r);
            }
        }
        String[] ability = aclType.ability();
        if (ArrayUtils.isNotEmpty(ability)) {
            ArrayNode abilities = putArray(acl, "ability");
            for (String r : ability) {
                abilities.add(r);
            }
        }

        acl.put("allOf", aclType.allOf());
        acl.put("oneOf", aclType.oneOf());
        acl.put("except", aclType.except());
    }


    @Override
    public Class[] supports() {
        return new Class[]{ACLType.class};
    }
}
